/**
 * 按钮发送验证码后自动置灰组件，60秒后可用
 * @author: minzhang
 * @update: 2017-03-13
 */

import React, { PropTypes } from 'react';
import { Button } from 'antd';

let interval;

const CommonCodeBtn = React.createClass({
  getInitialState() {
    return {
      disabled: false,
			text: this.props.children,
			time: 59,
    };
  },
  handleClick() {
		
		this.setState({
      disabled: true,
			text: `重新发送(${this.state.time})`,
			time: this.state.time - 1
    });
		
		const onClick = this.props.onClick;
    onClick && onClick();

    interval = setInterval(() => {
			this.setState({
				text: `重新发送(${this.state.time})`,
				time: this.state.time - 1
			})
			if(this.state.time < 0) {
				clearInterval(interval);
				this.setState({
					disabled: false,
					text: '发送验证码',
					time: 59
				})
			}
		}, 1000);
  },
	componentWillUnmount () {
		if(interval) {
			clearInterval(interval);
			interval = undefined;
		}
	},
  render() {
    return (
      <Button
        {...this.props}
				disabled={this.state.disabled}
				children={this.state.text}
        onClick={this.handleClick}
      />
    );
  },
});

CommonCodeBtn.propTypes = {
  children: PropTypes.any,
  onClick: PropTypes.func,
};

export default CommonCodeBtn;